package cn.easybuy.dao.order;

import java.util.Iterator;

import cn.easybuy.utils.ShoppingCart;
import cn.easybuy.utils.ShoppingCartItem;

public class CartServiceImpl implements CartService {

	/**
	 * 	修改购物车商品数量
	 */
	public ShoppingCart modifyShoppingCart(String productId, Integer quantity, ShoppingCart cart) throws Exception {
		
		for (ShoppingCartItem item : cart.getItems()) {
			if (item.getProduct().getId().toString().equals(productId)) {
				//判断数量是否为0
				if (quantity <= 0) {
					cart.getItems().remove(item);
					break;
				} else {
					item.setQuantity(quantity);
				}
			}
		}
		//购物车总金额重新计算
		cart = calculate(cart);
		return null;
	}

	/**
	 * 	购物车总金额重新计算
	 */
	public ShoppingCart calculate(ShoppingCart cart) throws Exception {
		
		double sum = 0.0;
		
		for (ShoppingCartItem item : cart.getItems()) {
			sum += item.getQuantity() * item.getProduct().getPrice();
			item.setCost(item.getQuantity() * item.getProduct().getPrice());
		}
		cart.setSum(sum);
		return cart;
	}

}
